<template>
  <el-dialog
    v-model="state.dialogVisible"
    :append-to-body="true"
    :before-close="close"
    :close-on-click-modal="true"
    :close-on-press-escape="true"
    :destroy-on-close="true"
    top="5vh"
    :modal="model"
    :title="state.dialogTitle"
    :width="width"
  >
    <div>
      <vab-query-form>
        <vab-query-form-left-panel :span="24">
          <el-button icon="circle-plus" type="primary" @click="handleAdd">
            添加
          </el-button>
        </vab-query-form-left-panel>
      </vab-query-form>

      <el-table
        ref="tableRef"
        v-loading="tableOptions.loading"
        border
        stripe
        :data="tableOptions.dataList"
        :height="tableOptions.height"
        :cell-style="tableStyle.cellStyle"
        :header-cell-style="tableStyle.headerCellStyle"
        lazy
        :load="loadChildren"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'haschildren' }"
        @sort-change="handleSortChange"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
      >
        <el-table-column
          align="left"
          label="节点名称"
          prop="nodeName"
          width="280"
        />
        <el-table-column
          align="center"
          label="节点编号"
          prop="nodeCode"
          width="120"
        />
        <el-table-column
          align="center"
          label="级别"
          prop="nodeLevel"
          width="60"
        />
        <el-table-column
          align="center"
          label="状态"
          prop="statusDesc"
          width="60"
        />
        <el-table-column
          align="center"
          label="排序号"
          prop="orderNo"
          width="80"
        />
        <el-table-column
          align="center"
          label="备注"
          prop="remark"
          width="160"
        />
        <el-table-column align="center" fixed="right" label="操作" width="180">
          <template #default="{ row }">
            <el-button
              icon="Edit"
              size="small"
              type="warning"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              icon="Remove"
              size="small"
              type="danger"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <system-tree-node-edit
        ref="editRef"
        width="50%"
        @confirm="handleConfirmEdit"
      />
    </div>
  </el-dialog>
</template>
<script setup name="SystemTreeNode">
import { useMessage, useMessageBox } from "@/hooks/message";
import { filterTreeNode } from "@/utils/common";
import { getTableHeight } from "@/utils/util";
import {
  querySystemTreeNodeTable,
  querySystemTreeNode,
  deleteSystemTreeNode
} from "@/api/admin/system/systemtree/";
import SystemTreeNodeEdit from "./systemtreeNodeEdit.vue";
import { useTable } from "@/hooks/table";

const props = defineProps({
  title: {
    type: String,
    default: "配置数据"
  },
  width: {
    type: String,
    default: "30%"
  },
  model: {
    type: Boolean,
    default: true
  }
});
const emits = defineEmits(["confirm"]);

const tableRef = ref(null);
const editRef = ref(null);

const state = reactive({
  dialogTitle: props.title,
  dialogVisible: false,
  idMaps: new Map(),
  treeId: ""
});

const tableOptions = reactive({
  height: getTableHeight(2) - 30,
  autoLoad: false,
  isPage: false,
  queryForm: {
    treeId: "",
    id: "",
    pid: "0"
  },
  queryFunction: querySystemTreeNodeTable,
  ascs: ["order_no"]
});

const {
  tableStyle,
  queryTableData,
  handleSelectionChange,
  handleReset,
  handleResetQuery,
  handleRowClick,
  handleSizeChange,
  handleCurrentChange,
  handleSortChange
} = useTable(tableOptions, tableRef);

const queryApiData = async (pid, resolve) => {
  const params = {
    treeId: state.treeId,
    id: "",
    pid: "0"
  };
  if (pid) {
    params.id = "";
    params.pid = pid;
  }
  querySystemTreeNode(params).then(res => {
    if (res.code === 200) {
      const list = res.data;
      resolve(list);
    } else {
      resolve();
    }
  });
};

const loadChildren = async (tree, treeNode, resolve) => {
  state.idMaps.set(tree.id, { tree, treeNode, resolve });
  queryApiData(tree.id, resolve);
};

const handleAdd = () => {
  const row = {};
  row.treeId = state.treeId;
  editRef.value.show(row);
};

const handleEdit = row => {
  if (row.treeId) {
    editRef.value.show(row, false);
  } else {
    useMessage().error("未选中任何行");
  }
};

const handleDelete = row => {
  if (row && row.id) {
    useMessageBox()
      .confirm("删除的节点将无法恢复，是否继续")
      .then(() => {
        deleteSystemTreeNode(row.id).then(res => {
          if (res.code === 200) {
            useMessage().success("删除成功");
            //将父节点的懒加载数据清空
            tableRef.value.store.states.lazyTreeNodeMap.value[row.pid] = [];
            //判断父节点是否已经展开过
            const rtr = state.idMaps.get(row.pid);
            //如果父节点已经展开过
            if (rtr) {
              loadChildren(rtr.tree, rtr.treeNode, rtr.resolve);
            } else {
              queryTableData({ treeId: state.treeId, id: "", pid: "0" });
            }
          } else {
            useMessage().success(res.msg);
          }
        });
      });
  }
};

const show = row => {
  state.treeId = row.id;
  queryTableData({ treeId: state.treeId });
  state.dialogVisible = true;
};

const close = () => {
  state.dialogTitle = props.title;
  state.dialogVisible = false;
  handleReset();
};

const save = () => {
  emits("confirm", {});
  close();
};

const handleConfirmEdit = pid => {
  nextTick(async () => {
    const rtr = state.idMaps.get(pid);
    //如果父节点已经展开过
    if (rtr) {
      await loadChildren(rtr.tree, rtr.treeNode, rtr.resolve);
    } else {
      //如果父节点没有展开过
      const pNode = filterTreeNode(tableOptions.dataList, pid, "id");
      //且父节点不属于根节点
      if (!pNode) {
        querySystemTreeNode({
          treeId: state.treeId,
          pid: pid
        }).then(res => {
          if (res.code === 200) {
            const list = res.data;
            //如果当前修改节点是根节点
            if (pid === "0") {
              //将table的结果赋值为查询结果
              tableOptions.dataList = list;
            } else {
              //否则修改父节点的懒加载结果
              tableRef.store.states.lazyTreeNodeMap.value[pid] = list;
            }
          }
        });
      } else {
        queryTableData({ pid: pid });
      }
    }
  });
};

defineExpose({
  show,
  close,
  save
});
</script>
<style lang="scss" scoped></style>
